import psycopg2

dbname = "dbname"
user = "user"
password = "password"
host = "host"
port = "port"

conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)

cur = conn.cursor()

async def set_col(user_id, name, surname, age, phone_number, graduated, sex):
    cur.execute("INSERT INTO users (user_id, name, age, phone_number, surname,  graduated, sex) VALUES (%s, %s, %s, %s, %s, %s, %s)", (user_id, name, age, phone_number, surname, graduated, sex ))
    conn.commit()

async def search_user_id(userid):
    cur.execute("SELECT user_id FROM users WHERE user_id = %s", (userid,))
    uid = cur.fetchone()
    if uid is not None:
        return uid[0]
    else:
        return False

async def show_id(userid):
    cur.execute("SELECT name, age, phone_number, surname, graduated, sex  FROM users WHERE user_id = %s", (userid,))
    user_info = cur.fetchone() 
    if user_info is not None:
        return user_info
    else:
        return False
    

async def update_user_info(user_id, name=None, age=None, phone_number=None, surname=None, graduated=None, sex=None):
    if name:
        cur.execute("UPDATE users SET name = %s WHERE user_id = %s", (name, user_id))
    if age:
        cur.execute("UPDATE users SET age = %s WHERE user_id = %s", (age, user_id))
    if phone_number:
        cur.execute("UPDATE users SET phone_number = %s WHERE user_id = %s", (phone_number, user_id))
    if surname:
        cur.execute("UPDATE users SET surname = %s WHERE user_id = %s", (surname, user_id))
    if graduated:
        cur.execute("UPDATE users SET graduated = %s WHERE user_id = %s", (graduated, user_id))
    if sex:
        cur.execute("UPDATE users SET sex = %s WHERE user_id = %s", (sex, user_id))
    conn.commit()


async def select_poll():
    cur.execute("SELECT poll FROM polls ORDER BY doc_id DESC LIMIT 5")
    uid = cur.fetchall()
    if uid is not None:
        return uid
    
async def set_answer(user_id, poll_id, answer):
    cur.execute("INSERT INTO answers (user_id, doc_id, answers) VALUES (%s, %s, %s)", (user_id, poll_id, answer))
    conn.commit()